package com.solon.open.controller;

import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.solon.open.entity.QaReq;
import com.solon.open.model.QaModelBM25;
import com.solon.open.service.QaBm25Service;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.UploadedFile;
import org.ttzero.excel.reader.ExcelReader;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Controller
public class QaBm25Controller {
    @Inject
    private QaBm25Service qaBm25Service;

    /**
     * 导入qa测试数据
     * @param file
     * @return
     * @throws NoApiKeyException
     * @throws UploadFileException
     * @throws IOException
     */
    @Mapping("/upload/bm25/qa")
    @Post
    public String upload(UploadedFile file) throws NoApiKeyException, UploadFileException, IOException {
        try (ExcelReader reader = ExcelReader.read(file.getContent())) {
            List<QaModelBM25> qaModels = reader.sheet(0)
                    .rows()// 读取数据行
                    .map(row -> row.to(QaModelBM25.class))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            qaBm25Service.addQa(qaModels);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "success";
    }

    /**
     * 问答
     * @param req
     * @return
     * @throws NoApiKeyException
     * @throws UploadFileException
     */
    @Mapping("/bm25/question")
    @Post
    public String question(@Body QaReq req) throws NoApiKeyException, UploadFileException {
        return qaBm25Service.getQa(req.getQuestion());
    }
}